package com.v1.video.util;

import java.util.HashMap;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import android.content.ContentResolver;
import android.content.Context;
import android.database.Cursor;
import android.net.Uri;
import android.provider.ContactsContract.CommonDataKinds.Phone;
import android.provider.ContactsContract.Data;

public class ContactUtil {

	private String[] projection = {Phone.NUMBER, Phone.DISPLAY_NAME};
	
	/**
	 * 获取本地通讯录，返回值为HashMap<姓名，电话>
	 * 
	 * @param context
	 * @return
	 */
	public HashMap<String, String> getContact(Context context){
		
		Uri uri = Data.CONTENT_URI; // 联系人Uri
		ContentResolver resolver = context.getContentResolver();
		Cursor phoneCursor = resolver.query(uri, projection, null, null,  
				null);
		
		HashMap<String, String> contactMap = new HashMap<String, String>();
		
		if(phoneCursor != null) {
			while(phoneCursor.moveToNext()){
				
				String name = null;
				String num = null;
				
				if(phoneCursor.getString(phoneCursor.getColumnIndex(Phone.NUMBER)) != null){
					num = phoneCursor.getString(phoneCursor.getColumnIndex(Phone.NUMBER));
				}
				if(phoneCursor.getString(phoneCursor.getColumnIndex(Phone.DISPLAY_NAME)) != null){
					name = phoneCursor.getString(phoneCursor.getColumnIndex(Phone.DISPLAY_NAME));
				}
				if(num != null && name != null){
					num = formatNum(num);
					if(!num.equals(name) && checkPhoneNum(num)){
						
						contactMap.put(name, num);
						
					}
					
				}
				
			}
			
		}
		
		return contactMap;
		
	}
	
	private boolean checkPhoneNum(String num){
		
		Pattern p = Pattern.compile("^((1[0-9][0-9])|(1[0-9][^4,\\D])|(1[0-9][0,5-9]))\\d{8}$");  
		Matcher m = p.matcher(formatNum(num));
		return m.matches(); 
		
	}
	
	/**
	 * 过滤电话中的前置“+86”和中间的空格符号
	 * @param num
	 * @return
	 */
	private String formatNum(String num){
	    return num.trim().replace("+86", "").replaceAll(" ", "");
	}
}
